const BaseRest = require('./base.js');

/**
 * 用户标签管理
 * @type {module.exports}
 */
module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    // 重载，改变默认规则
    this.modelInstance = this.model('role_auth');
  }

  async getAction() {
    let data = {};
    const map = {};
    // 获取详情
    if (this.id) {
      map.id = this.id;
      data = await this.modelInstance.where(map).find();
      return this.success(data);
    }

    /// / 关键词
    // const key = this.get('key');
    // if(key) {
    //	map['title|path'] = ['like', '%' + key + '%'];
    // }

    if (this.get('role_id')) {
      map['role_id'] = this.get('role_id');
    }

    if (this.get('all')) {
      data = await this.modelInstance.where(map).order('id asc').select();
      return this.success(data);
    }

    const page = this.get('page') || 1; // 页码
    const pageSize = this.get('pageSize') || 50; // 每页显示数量
    data = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
    return this.success(data);
  }

  async postAction() {
    const data = this.post();
    const path = this.post('path');

    if (think.isEmpty(path)) {
      return this.fail(-1, '添加失败');
    }

    const auth = await this.modelInstance.where({path: path}).find();
    if (!think.isEmpty(auth)) {
      return this.fail(-1, '路由已经存在');
    }
    data['id'] = await think.uuid('v1');
    const ret = await this.modelInstance.add(data);
    return this.success(ret);
  }

  /**
	 * 删除内容
	 * @return {[type]} [description]
	 */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '记录不存在');
    }

    const rows = await this.modelInstance.where({
      id: this.id
    }).delete();

    if (rows) {
      // await this.hook('contentDelete', {id: this.id});
      return this.success({
        affectedRows: rows
      }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }

  // async putAction() {
  //	if (!this.id) {
  //		return this.fail('params error');
  //	}
  //	const pk = this.modelInstance.pk;
  //	const data = this.post();
  //
  //	think.logger.info(data);
  //
  //	data[pk] = this.id;
  //	if (think.isEmpty(data)) {
  //		return this.fail('data is empty');
  //	}
  //	const rows = await this.modelInstance.where({ [pk]: this.id }).update(data);
  //	if (rows) {
  //		await this.hook(this.resource + 'Update', data);
  //		return this.success({ affectedRows: rows }, '更新成功');
  //	} else {
  //		return this.fail(1000, '更新失败');
  //	}
  // }
};
